package com.test.mina2.example.message;

import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;

import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.CumulativeProtocolDecoder;
import org.apache.mina.filter.codec.ProtocolDecoderOutput;

public class CmccSpicDecoder extends CumulativeProtocolDecoder {
	private final Charset charSet;

	public CmccSpicDecoder(Charset charSet) {
		this.charSet = charSet;
	}

	@Override
	protected boolean doDecode(IoSession session, IoBuffer in, ProtocolDecoderOutput out) throws Exception {

		IoBuffer ioBuffer = IoBuffer.allocate(100).setAutoExpand(true);
		CharsetDecoder decoder = charSet.newDecoder();
		int matchCount = 0;
		String statusLine = "";
		String sender = "";
		String receiver = "";
		String length = "";
		String sms = "";
		int line = 1;
		while (in.hasRemaining()) {
			byte b = in.get();
			ioBuffer.put(b);
			if (b == 10 && line < 5) {
				matchCount++;
				if (line == 1) {
					ioBuffer.flip();
					statusLine = ioBuffer.getString(matchCount, decoder);
					statusLine = statusLine.substring(0, statusLine.length() - 1);
					matchCount = 0;
					ioBuffer.clear();
				}

				if (line == 2) {
					ioBuffer.flip();
					sender = ioBuffer.getString(matchCount, decoder);
					sender = sender.substring(0, sender.length() - 1);
					matchCount = 0;
					ioBuffer.clear();
				}

				if (line == 3) {
					ioBuffer.flip();
					receiver = ioBuffer.getString(matchCount, decoder);
					receiver = receiver.substring(0, receiver.length() - 1);
					matchCount = 0;
					ioBuffer.clear();
				}
				if (line == 4) {
					ioBuffer.flip();
					length = ioBuffer.getString(matchCount, decoder);
					length = length.substring(0, length.length() - 1);
					matchCount = 0;
					ioBuffer.clear();
				}

				line++;
			} else if (line == 5) {
				matchCount++;
				if (matchCount == Long.parseLong(length.split(":")[1])) {
					ioBuffer.flip();
					sms = ioBuffer.getString(matchCount, decoder);
					line++;
					break;
				}
			} else {
				matchCount++;
			}
		}
		SmsObject smsObject = new SmsObject();
		smsObject.setSender(sender.split(":")[1]);
		smsObject.setReceiver(receiver.split(":")[1]);
		smsObject.setMessage(sms);
		out.write(smsObject);
		return false;
	}
}
